package com.leyou.user.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.service.IUserService;
import com.leyou.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author xiuer
 * @description 用户注册控制层
 * @create 2019/7/6 20:21
 */
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户数据的校验
     *
     * @param data 校验的数据
     * @param type 1. 用户名，2 手机
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> verifyUserMsg(@PathVariable("data") String data,
                                                 @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.verifyUserMsg(data, type));
    }

    /**
     * 发送手机验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendPhoneCode(@RequestParam("phone") String phone) {
        userService.sendPhoneCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册业务
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid UserDTO userDTO, BindingResult result, @RequestParam("code") String code) {
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("【】"));
            throw new LyException(400, msg);
        }
        userService.register(userDTO, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     */
    @GetMapping("query")
    public ResponseEntity<UserVO> queryUserInfo(@RequestParam("username") String username,
                                                @RequestParam("password") String password, HttpServletRequest request) {

        return ResponseEntity.ok(userService.queryUserInfo(username, password));
    }
}
